
const express = require('express');
const cors = require('cors');
const { spawn } = require('child_process');
const app = express();
let uavProcess={
  name: 'pushMedia/uavPush.py',
  process:null,
  flvUrl:'http://localhost:3001/live/uav.flv'
}
// 启动子进程
let openProcess=function(ProcessObj){
    closeProcess(ProcessObj)
    // 启动Python脚本
    ProcessObj.process = spawn('python', [uavProcess.name]);
    
    // 监听Python脚本的输出
    ProcessObj.process.stdout.on('data', (data) => {
        console.log(`stdout: ${data}`);
    });
    
    ProcessObj.process.stderr.on('data', (data) => {
        console.error(`stderr: ${data}`);
    });
    
    ProcessObj.process.on('close', (code) => {
        console.log(`child process exited with code ${code}`);
    });

}
// 关闭子进程
let closeProcess=function(ProcessObj){
  if(ProcessObj.process){
    ProcessObj.process.kill(); // 强制终止子进程
    ProcessObj.process=null
  }
}
// 用于解析JSON格式的请求体
app.use(express.json());
// 允许所有域名访问
app.use(cors());

// 定义POST请求的路由和处理函数
app.post('/flvURL', (req, res) => {
    // req.body 包含解析后的JSON数据
    const data = req.body;

    // 根据需要处理数据
    console.log('Received POST data:', data);
    if(data.target==='无人机' && data.type===1){
      openProcess(uavProcess)
          // 发送响应
       res.status(200).json({
           flvUrl:uavProcess.flvUrl
       });
    }
});

const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Express server running at http://localhost:${PORT}`);
});